/**
 * @jQueryPlug 
 * @desc 将星级显示初始化
 * @example
 * // 在每次模板更新的之后，初始化星星
 * $(".some-start").initStart({
 *      totalStart:5, //星级的总数  
 *      enableChoice:false, //是否启动编辑
 *      onChange: function(start){}, //接受编辑的值
 * })
 */
(function($) {
    var isbind = false;
    var defaultCfg = {
        totalStart: 5,
        enableChoice: false,
        onChange: function(start) {
            alert("defaultCfg");
        }
    }
    $.fn.extend({
        initStart: function(cfg) {
            var _cfg = $.extend({}, defaultCfg, cfg);
            return $(this).each(function() {
                var $this = $(this);
                var start = $this.data('start');
                if (isNaN(start)) return;
                $this.children().remove();
                $(this).append($(proStart(start, _cfg)));
                var $that = $(this);
                if (_cfg.enableChoice) {
                    if(isbind) return;
                    isbind = true;
                    $this.on('click', 'em', function() {
                        start = $(this).index() + 1;
                        $that.children().remove();
                        $that.append($(proStart(start, _cfg)));
                        _cfg.onChange && _cfg.onChange(start);
                    })
                }
            })
        }
    })

    function proStart(start, cfg) {
        var startStr = "";
        for (var i = 0; i < cfg.totalStart; i++) {
            if (i < start) {
                startStr += '<em class=\"onstar\"></em>';
            } else {
                startStr += '<em class=\"unstar\"></em>';
            }
        }
        return startStr;
    }

})(jQuery)

var servicevote = {
    init: function() {
        var that = this;
        that.getAddress(10, '', $("select[data-name=Aprovince]"));
        that.getAddress(20, '', $("select[data-name=Acity]"));
        that.getAddress(30, '', $("select[data-name=Atown]"));
        $.ajaxSend('api/CompanyApply/GetList?token=' + $.cookie('token'), {
            "page": 1,
            "pagesize": 20,
            "companyname": '',
            "cityid": ''
        }, function(redata) {
            if (redata.recode == '1003') {
                window.location.href = '/nlogin.html';
                return;
            }
            if (redata.recode == '0000' && redata.mod != null) {

                var compiled = _.template($("#servicevoteTpl").html());
                $("#servicevoteCon").html(compiled(redata.mod));

                $("#servicevotePage").show().jqPaginator({
                    //totalPages: Math.ceil(redata.mod.TotalNum/20),
                    totalPages: redata.mod.TotalPageCount ? redata.mod.TotalPageCount : 1,
                    visiblePages: 5,
                    currentPage: 1,
                    first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                    prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"><\/i>上一页<\/a><\/li>',
                    next: '<li class="next"><a href="javascript:void(0);">下一页<i class="arrow arrow3"><\/i><\/a><\/li>',
                    last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                    page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                    onPageChange: function(num, type) {

                        $("#servicevotePage").attr('curpage', num);
                        $("#shpage").val(num);
                        if (type == 'change') {
                            that.doPage();
                        }
                    }
                });


                $("#servicevoteCon").on("click", '.jApplyPass', function() {
                    var wuliu_id = $(this).attr('wuliu_id'),
                        wuliu_no = $(this).attr('wuliu_no'),
                        wuliu_name = $(this).attr('wuliu_name');
                    $.ajax({
                        url: COMMONURL + 'api/CompanyApply/Apply?token=' + $.cookie('token'),
                        type: 'post',
                        dataType: 'json',
                        data: {
                            wuliu_id: wuliu_id,
                            wuliu_no: wuliu_no,
                            wuliu_name: wuliu_name
                        }

                    }).done(function(data) {
                        if (redata.recode == '0000') {
                            alert('操作成功');
                            window.location.reload();
                        }
                    })
                })


            } else {
                var compiled = _.template($("#servicevoteTpl").html());
                $("#servicevoteCon").html(compiled(redata.mod));
            }
        });

        $("#servicevoteQuery").click(function() {
            that.doSearch();
        });



        //显示评价窗口
        $('#servicevoteCon').on('click', '.J_vote', function() {
            // 初始化输入值
            $("[data-start]").initStart({
                totalStart: 5,
                enableChoice: true,
                onChange: function(start) {
                    $('[name=score]').val(start);
                }
            })
            $('[name=score]').val('0');
            $('[name=wuliu_id]').val($(this).data('wuliu-id'));
            $('[name=comment_info]').val('');

            // 显示窗口
            $("#vote-model").modal();

        });

        // 初始化评论的提交
        this.initVoteSubmit();
    },
    getAddress: function(type, sub, obj) {
        $.ajax({
            url: COMMONURL + 'api/CityBase/GetCityBaseList?token=' + $.cookie('token'),
            type: 'post',
            dataType: 'json',
            data: {
                type: type,
                sub_city_id: sub
            }

        }).done(function(data) {
            var arry = [];
            if (!!data.mod) {
                if (!data.mod.length) {
                    arry.push('<option value="' + '" data-id="' + '">' + '请选择' + '</option>');
                } else {
                    $.each(data.mod, function(i, v) {
                        arry.push('<option value="' + v.city_name + '" data-id="' + v.city_id + '">' + v.city_name + '</option>');
                    });
                }
                obj.html(arry.join(''));
            }

        })
    },
    doPage: function() {
        var page = $.trim($("#shpage").val());
        $.ajax({
            url: COMMONURL + "api/CompanyApply/GetList?token=" + $.cookie('token'),
            type: "post",
            data: {
                page: page,
                pagesize: 20,
                companyname: $("#CompanyInp").val(),
                cityid: '',
            },
            dataType: "json"
        }).done(function(redata) {
            if (redata.recode == '0000' && redata.mod != null) {
                var compiled = _.template($("#servicevoteTpl").html());
                $("#servicevoteCon").html(compiled(redata.mod));
            } else {
                var compiled = _.template($("#servicevoteTpl").html());

                $("#servicevoteCon").html(compiled(redata.mod));
                $("#servicevotePage").hide();
            }
        });
    },
    doSearch: function() {
        var page = $.trim($("#shpage").val());
        $.ajax({
            url: COMMONURL + "api/CompanyApply/GetList?token=" + $.cookie('token'),
            type: "post",
            data: {
                page: page,
                pagesize: 20,
                companyname: $("#CompanyInp").val(),
                cityid: '',
            },
            dataType: "json"
        }).done(function(redata) {
            if (redata.recode == '0000' && redata.mod != null) {
                var compiled = _.template($("#servicevoteTpl").html());
                $("#servicevoteCon").html(compiled(redata.mod));
                $("#servicevotePage").show().jqPaginator({
                    //totalPages: Math.ceil(redata.mod.TotalNum/20),
                    totalPages: redata.mod.TotalPageCount ? redata.mod.TotalPageCount : 1,
                    visiblePages: 5,
                    currentPage: 1,
                    first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                    prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"><\/i>上一页<\/a><\/li>',
                    next: '<li class="next"><a href="javascript:void(0);">下一页<i class="arrow arrow3"><\/i><\/a><\/li>',
                    last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                    page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                    onPageChange: function(num, type) {
                        $("#servicevotePage").attr('curpage', num);
                        $("#shpage").val(num);
                        if (type == 'change') {
                            that.doPage();
                        }
                    }
                });
            } else {
                var compiled = _.template($("#servicevoteTpl").html());

                $("#servicevoteCon").html(compiled(redata.mod));
                $("#servicevotePage").hide();
            }
        });
    },
    initVoteSubmit: function() {
        $("#saleAddForm").validate({
            rules: {
                wuliu_id: "required",
                score: 'required',
                comment_info: 'required',
            },
            messages: {
                score: "请选择评分",
                comment_info: '请输入心得',
            },
            submitHandler: function(form) {
                $.ajax({
                    url: COMMONURL + "api/BidDispute/AddComment?token=" + $.cookie('token'),
                    type: "post",
                    dataType: "json",
                    data: {
                        wuliu_id: $('[name=wuliu_id]').val(),
                        score: $('[name=score]').val(),
                        comment_info: $('[name=comment_info]').val(),
                    }
                }).done(function(data) {
                    if (data.recode == 0000) {
                        $('.vote-model').modal("hide");
                        alert("点评成功");
                    } else {
                        alert(data.resmessage);
                    }
                })
            }
        })
    }
}

servicevote.init();
